<?php
/**
 * Description of TParser
 *
 * @author ADM
 */
class TParser extends CComponent
{
    public $highlightCssClass='hl-code';
    
    protected $config;

    public function __construct($srcLineNumbers = false, $purify = false)
    {
        if(!class_exists('Text_Highlighter', false)) {
            require_once(Yii::getPathOfAlias('system.vendors.TextHighlighter.Text.Highlighter').'.php');
            require_once(Yii::getPathOfAlias('system.vendors.TextHighlighter.Text.Highlighter.Renderer.Html').'.php');
            $this->config['use_language'] = true;
            if($srcLineNumbers) $this->config['numbers'] = HL_NUMBERS_LI;
            $this->config['purify'] = $purify;
        }
    }

    public function transform($content)
    {
        $patterns = array(
                          "/(<)(\w+)(-code>)(.*?)(<\/)(\\2-code>)/mse",
                          "/(<execute>)(.*?)(<\/execute>)/mse"
                         );
        $replace = array(
                         "\$this->parseBlock('\\4', '\\2')",
                         "eval('\\2')"
                         );
        $content = preg_replace($patterns, $replace, $content);
        if($this->config['purify'])
        {
            $purifier=new CHtmlPurifier;
            $content = $purifier->purify($content);
        }
        return $content;
    }

    public function parseBlock($text, $lang = null)
    {
        $hlSQL = Text_Highlighter::factory($lang);
        $hlSQL->setRenderer(new Text_Highlighter_Renderer_Html($this->config));
        $text = $hlSQL->highlight($text);
        return "<div class=\"{$this->highlightCssClass}\">".$text."</div>";
    }
}
?>
